<template>
    <div class="renderCheckin">

        <!-- 添加租客 -->
        <Modal
            v-model="showAddRenter"
            :loading="true"
            title="添加租客">

            <Form ref="addForm" :model="formItem" :rules="ruleValidate2" :label-width="100" :show-message="false">
                <FormItem label="租客姓名" prop="name">
                    <Input v-model="formItem.name" :maxlength="20" placeholder="租客姓名"/>
                </FormItem>
                <FormItem label="租客电话" prop="phone">
                    <Input v-model="formItem.phone" :maxlength="11" placeholder="租客电话">
                        <Select v-model="formItem.country_code" slot="prepend" style="width: 110px">
                            <Option v-if="item.code === '86'" v-for="item in CountryCodes" :key="item.code" :value="item.code">{{item.country}}</Option>
                        </Select>
                    </Input>
                </FormItem>
                <FormItem label="身份证号" prop="id_card">
                    <Input v-model="formItem.id_card" :maxlength="18" placeholder="身份证号(可选)"></Input>
                </FormItem>
            </Form>

            <div slot="footer">
                <Button type="ghost" size="large" @click="cancelAddRenter('addForm')">取消</Button>
                <Button type="primary" size="large" @click="confirmAddRenter('addForm')">保存</Button>
            </div>
        </Modal>

        <!-- 租客入住 -->
        <Modal
            :value="!showAddRenter && isModalVisible"
            :closable="false"
            :mask-closable="false"
            :loading="true"
            title="租客入住"
            width="750">

            <Form ref="checkInForm" :model="checkInFormItem" :label-width="100"
            style="height: 100%;">

                <FormItem class="mb10" label="搜索租客" style="width:480px;display:inline-block;margin-right:12px;margin-bottom:6px" v-if="room">
                    <Select
                        filterable
                        clearable
                        remote
                        placeholder="租客姓名/手机号"
                        :remote-method="remoteRenterMethod"
                        @on-change="selectRenter"
                        :loading="loadingRenter">
                        <Option v-for="(option, index) in searchedRenters" :label="option.name" :value="''+option.id" :key="option.name + option.id">{{option.name +'-'+ option.phone}}</Option>
                    </Select>
                </FormItem>

                <Button type="ghost" @click="addRenter" v-if="room" :loading = "isLoadig" style="width:124px">
                    <Icon type="plus-round"></Icon> 添加租客
                </Button>

                <Row class="renter-list-cells" style="margin-bottom:10px">
                    <Col class="renter-info" span="4" style="padding-right:22px;text-align:right;width:100px;">租客姓名</Col>
                    <Col class="renter-info" span="4">{{ renter.name|| '-' }}</Col>
                    <Col class="renter-info" span="15">
                        <Button type="ghost" @click="addCorenter" style="float:right;width:124px;margin-right:45px" v-if="isShowAddCoRenter">
                            <Icon type="plus-round"></Icon> 增加同租人
                        </Button>
                    </Col>
                </Row>
                <Row class="renter-list-cells" style="margin-bottom:10px">
                    <Col class="renter-info" span="4" style="padding-right:22px;text-align:right;width:100px;">租客电话</Col>
                    <Col class="renter-info" span="4">{{ renter.phone|| '-' }}</Col>
                </Row>

                <Row class="renter-list-info" v-show="coRenterNumber" style="padding:0;margin-bottom:14px">
                    <Col span="4" style="padding-right:22px;text-align:right;padding-top:13px">同租人信息</Col>
                    <Col span="20">
                        <renterCo
                        v-for="(item,index) in corentersData"
                        @addCorenterData="addCorenterData"
                        @removeCorenterData="removeCorenterData"
                        :corIndex="index"
                        :key="index">
                        </renterCo>
                    </Col>
                </Row>

                <FormItem class="mb10" label="房间信息" v-if="home && room">
                    <Col span="24">{{ getHomeAddr() }} - 房间{{roomInfo.room_name}}</Col>
                </FormItem>

                <div v-if="!room">
                    <FormItem class="mb10" label="房源地址" >
                        <Select
                            class="cursor-text"
                            filterable
                            remote
                            placeholder="请输入小区/房源编号"
                            :remote-method="remoteMethod"
                            @on-change="selectRoom"
                            :loading="loadingHome">
                            <Option
                            v-for="(option, index) in homes"
                            :value="''+option.id"
                            :label="option.city + option.district + option.address +' (房源编号:'+option.home_name+')'"
                            :key="option.id">{{option.city + option.district + option.address +' (房源编号:'+option.home_name+')'}}</Option>
                        </Select>
                    </FormItem>

                    <!-- 通过房间名模糊搜索 -->
                    <FormItem class="mb10" label="房间号">
                        <Select
                            @on-change="getRoomInfo"
                            :remote-method="getRooms"
                            :loading="loadingRoom"
                            :placeholder="'请输入房间名'"
                            remote
                            filterable>
                            <Option
                            v-for="option in rooms"
                            :value="option.id+''"
                            :label="option.room_name"
                            :key="option.id">{{ option.room_name }} {{option.building && option.building.room_name ? `- ${option.building.room_name}` : ''}}</Option>
                        </Select>
                    </FormItem>
                </div>

                <FormItem class="mb10" label="租约有效期">
                    <DatePicker
                    type="datetime"
                    placement="bottom"
                    placeholder="租约结束日期"
                    :options="options5"
                    @on-open-change="handleTimePickerChange2"
                    v-model="checkInDateEnd"
                    style="width: 49%;float:right"></DatePicker>

                    <div style="display:inline-block;text-align:center;width:2%;float:right">-</div>

                    <DatePicker
                    type="datetime"
                    placement="bottom"
                    placeholder="租约开始日期"
                    :options="options5"
                    @on-open-change="handleTimePickerChange"
                    v-model="checkInDateStart"
                    style="width: 49%;float:right"></DatePicker>
                </FormItem>

                <div class="lock-wrap" v-if="lockLoading">
                    <Spin size="small"></Spin>
                </div>
                <div v-if="hasLock">
                    <div class="split-line" ></div>

                    <FormItem class="mb10" label="安全配置">
                        <Checkbox v-if="passwordType === 1" :disabled="!hasOutLock" style="margin-left:10px" v-model="isSendOutDoorPwd"> 同时下发外门锁密码</Checkbox>

                        <Checkbox style="margin-left:10px" v-model="smsWithHome"> 短信携带公寓信息</Checkbox>

                        <Checkbox style="margin-left:10px" v-model="deleteAllNotRenterPassword" :disabled="!canBatchDeletePwds">删除房间内所有非租客密码</Checkbox>
                    </FormItem>

                    <FormItem class="mb10" label="门锁密码">
                        <Row>
                            <Col span="10">
                                <FormItem class="mb10" prop="startDate">
                                    <Select v-model="passwordType">
                                        <Option v-for="item in passwordTypes" :value="item.value" :key="item.value">{{ item.label }}</Option>
                                        <Option :value="fingerType.value" :key="fingerType.value" v-if="isFingerLock">{{ fingerType.label }}</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                        </Row>
                    </FormItem>

                    <FormItem class="mb10" label="密码下发方式">
                        {{isShowUnableTip ? '门锁离线，为安全保障，租约开始时间超过7天，不下发密码' : sendPasswordType}}
                    </FormItem>

                    <FormItem class="mb10" label="密码有效期">
                        <DatePicker
                        type="datetime"
                        placement="top"
                        placeholder="密码结束日期(可选)"
                        :options="passwordDateEndOptions"
                        v-model="passwordDateEnd"
                        style="width: 49%;float:right"></DatePicker>

                        <div style="display:inline-block;text-align:center;width:2%;float:right">-</div>

                        <!-- 离线密码下发 不让输入有效期-->
                        <Input
                        v-if="hasNoGatewayLock"
                        style="width: 49%;float:right"
                        :disabled="true"
                        :value="new Date(passwordDateStart).Format('yyyy-MM-DD HH:mm')">
                        </Input>
                        <DatePicker
                        v-else
                        type="datetime"
                        placement="top"
                        placeholder="密码开始日期(可选)"
                        :options="options5"
                        v-model="passwordDateStart"
                        style="width: 49%;float:right"></DatePicker>
                    </FormItem>
                </div>

                <!-- <FormItem class="mb10" label="提示:" v-if="hasLock">
                    <div>无网关/离线 门锁仅支持发放激活码,激活码使用后即失效。</div>
                </FormItem> -->

                <div class="split-line"></div>

                <div class="access-control-wrap" v-if="accessLoading || m3AccessLoading">
                    <Spin size="small"></Spin>
                </div>

                <div v-if="guardDevices.length && !accessLoading">
                    <FormItem label="授权人脸门禁">
                        <CheckboxGroup v-model="guardDeviceIds">
                            <Row v-if="publicDevice.length">
                                <Col span="4">
                                    <p style="float: right;padding-right: 10px">小区大门门禁:</p>
                                </Col>

                                 <Col span="20" style="text-align:center; display: flex;flex-wrap: wrap">
                                    <Checkbox :label="device.id" :key="index" v-for="(device, index) in publicDevice">{{device.description === '' ? '门禁' : device.description }}</Checkbox>
                                </Col>
                            </Row>

                             <Row v-if="privateDevice.length">
                                <Col span="4">
                                    <p style="float: right;padding-right: 10px">单元门门禁:</p>
                                </Col>

                                <Col span="20" style="text-align:center; display: flex;flex-wrap: wrap">
                                    <Checkbox :label="device.id" :key="index" v-for="(device, index) in privateDevice">{{device.description === '' ? '门禁' : device.description }}</Checkbox>
                                </Col>
                            </Row>
                        </CheckboxGroup>
                    </FormItem>
                    <!-- <div class="split-line"></div> -->
                </div>

                <div v-if="guardM3Devices.length && !m3AccessLoading">
                    <FormItem label="授权m3门禁">
                        <CheckboxGroup v-model="guardM3DevicesIds">
                            <Row>
                                <Col span="4">
                                    <p style="float: right;padding-right: 10px">小区大门门禁:</p>
                                </Col>

                                 <Col span="20" style="text-align:center; display: flex;flex-wrap: wrap">
                                    <Checkbox :label="device.id" :key="device.id" v-for="(device, index) in guardM3Devices">{{device.description === '' ? 'M3门禁' : device.description }}</Checkbox>
                                </Col>
                            </Row>
                        </CheckboxGroup>
                    </FormItem>
                </div>

                <FormItem class="mb10" label="房源公摊配置" v-if="roomInfo && roomInfo.id">

                    <Poptip @on-popper-show="handlePopperShow">
                        <Button>查看入住后各房间公摊比例</Button>
                        <div slot="title">房源公摊配置</div>
                        <div slot="content" class="pool-content">
                            <div>当前公摊 : {{poolConfig.use_pool ? '已开启':'未开启'}}</div>
                            <div v-if="poolConfig.use_pool">公摊模式 : {{ poolConfig.pool_type === 1 ? '均摊':'按比例分摊' }}</div>
                            <div style="display:flex;" v-if="poolConfig.use_pool && poolConfig.pool_type===2">
                                <div style="padding-right:10px">公摊比例 : </div>
                                <div style="flex:1" class="clear-fix">
                                    <div class="fl" style="width:50%" v-if="item.ratio" v-for="item in rooms">{{item.room_name}} :
                                        {{ (  (item.ratio * 100||0)/getTotalRatios(rooms) ).toFixed(0)  }} %
                                    </div>
                                </div>
                            </div>
                        </div>
                    </Poptip>
                    <span v-if="hasLock && hasNoGatewayLock" style="margin-left:20px;color:red">当前有门锁离线或无网关，只能下发离线密码, 并且有效期不超过一年</span>

                </FormItem>

                <Row v-if="hasElemeter" class="mb10" style="font-size:13px;">
                    <Col span="14" v-if="overdraft" style="text-align:center;">
                        当前电表读数：{{ roomInfo.electric_read }} 度{{roomInfo.updated_at ? '（更新于'+new Date(roomInfo.updated_at).Format('yyyy/MM/dd')+'）' : ''}}
                    </Col>
                    <Col span="14" v-if="!overdraft" style="text-align:center;">
                        当前剩余电量：{{ leftElectric }} 度 {{roomInfo.updated_at ? '（更新于'+new Date(roomInfo.updated_at).Format('yyyy/MM/dd')+'）' : ''}}
                    </Col>
                    <Col span="10" v-if="!overdraft">
                        <CheckboxGroup v-model="checkInFormItem.interest">
                            <Checkbox label="剩余电量清零" v-model="isResetElemeter"></Checkbox>
                        </CheckboxGroup>
                    </Col>
                </Row>


            </Form>

            <div slot="footer">
                <Button type="text" size="large" @click="cancelCheckIn('checkInForm')">取消</Button>
                <Button type="primary" :loading = "isLoadig" size="large" @click="confirmCheckIn('checkInForm')">入住</Button>
                <!-- <Button type="primary" :loading = "isLoadig" size="large" @click="isShowPwdModal = true;">入住</Button> -->
            </div>
        </Modal>

        <Modal title="租客入住" width="740" v-model="isShowPwdModal">
            <p>租客登记入住成功</p>

            <p v-if="showAccessControllTip && AccessControllTip">{{AccessControllTip}}</p>
            <p v-if="showM3AccessControllTip && M3AccessControllTip">{{M3AccessControllTip}}</p>

            <div v-if="isShowPwdTip">
                <p>新增门锁密码指令下发成功</p>

                <br/>
                <div v-if="Object.keys(this.batchResult).length">
                    <p>房间门上未关联租客密码删除{{this.batchResult.result === 'ok' ? '成功' : '失败'}}</p>

                    <div v-if="this.batchResult.activation_password_ids">
                        <p v-for="id in batchResult.activation_password_ids" :key="id">离线密码{{id}}当天下发，为保障安全，请于次日操作</p>
                    </div>
                </div>
            </div>

            <div slot="footer">
                <Button type="text" size="large" @click="doAfterCheckIn">确定</Button>
            </div>
        </Modal>

        <operateResultModal v-if="isResultModalVisible" @confirm="closeOutModal" :operateResult="operateResult"></operateResultModal>

    </div>
</template>

<script>
import validate from '@/libs/validate'
import util from '@/libs/util'
import { http, api } from '@/libs/http'
import { DeviceTypeEnum, CountryCodes } from '@/libs/const'
import renterCo from './renterCo.vue'
import operateResultModal from './operateResultModal'
import dayjs from 'dayjs'
import { mapState } from 'vuex'
export default {
  props: {
    renterId: {
      // 租客Id
      required: false
    },
    room: {
      // 房间id
      required: false
    },
    home: {
      // 房源信息
      required: false
    }
  },
  components: {
    renterCo,
    operateResultModal
  },
  data () {
    return {
      showM3AccessControllTip: false,
      M3AccessControllTip: '',
      homeLeaseType: -1, // 房源类型
      loadingRoom: false,
      AccessControllTip: '', // 门禁提示
      accessLoading: false, // 门禁是否正在加载
      m3AccessLoading: false, // m3门禁是否正在加载
      batchResult: {}, // 批量删除密码返回
      isShowPwdTip: false, // 入住成功弹窗是否展示密码相关
      isShowPwdModal: false, // 是否展示密码弹窗
      CountryCodes,
      deleteAllNotRenterPassword: false, // 是否删除所有非租客密码
      locks: [],
      lockLoading: false,
      hasLock: false, // 房间和公区是否有门锁
      canBatchDeletePwds: false, // 当前房间是否可以删除所有非管理员密码
      innerLockInfo: null,
      hasOutLock: false,
      searchedRenters: [],
      searchedRenter: '',
      coRenterNumber: 0, // 控制是否展示同租人选项
      loadingRenter: false,
      showAddRenter: false, // 显示添加租客弹窗
      isLoadig: false,
      renter: {},
      checkInRoomId: '', // 入住房间id
      checkInDateStart: '', // 租约开始日期
      checkInDateEnd: '', // 租约结束日期
      address: '', // 输入的关键字
      homes: [], // 关键字搜索到的房源
      homeId: '',
      rooms: [], // 搜索到的房间
      roomInfo: {}, // 具体房间信息
      parentRoomInfo: {}, // 公区房间
      loadingHome: false, // 是否正在搜索房源
      passwordType: 1, // 是否授权密码
      passwordDateEnd: '', // 密码结束日期
      passwordDateStart: '', // 密码开始日期
      isSendOutDoorPwd: true, // 发放外门密码
      smsWithHome: false, //  短信携带公寓信息
      isResetElemeter: false, // 是否清零电表
      corenters: 0, // 同租人总数
      corentersData: [], // 同租人数据
      isFingerLock: false, // 是否是指纹锁
      checkInFormItem: {
        // 租客入住参数
        co_tenants: [],
        lease_start: 0,
        lease_end: 0,
        note: ''
      },
      passwordTypes: [
        {
          value: 1,
          label: '授权密码'
        },
        {
          value: 0,
          label: '不授权'
        }
      ],
      fingerType: {
        value: 2,
        label: '指纹密码'
      },
      formItem: {
        // 添加租客参数
        name: '',
        phone: '',
        id_card: '',
        country_code: '86'
      },

      isModalVisible: true,
      isResultModalVisible: false,
      operateResult: [],
      guardDevices: [], // 门禁设备
      guardDeviceIds: [], // 授权门禁的id
      guardM3Devices: [], // M3门禁设备
      guardM3DevicesIds: [], // M3门禁设备授权id
      showAccessControllTip: false, // 是否展示门禁指令下发
      ruleValidate2: {
        name: [
          {
            required: true,
            message: '请输入租客姓名',
            trigger: 'change'
          }
        ],
        phone: [
          {
            required: true,
            message: '请输入租客手机号',
            trigger: 'change'
          },
          { validator: validate.validPhone, trigger: 'change' }
        ],
        id_card: [
          {
            required: false,
            message: '请输入身份证号码',
            trigger: 'change'
          }
          // { validator: validate.validIDCard, trigger: 'blur' }
        ]
      },

      options5: {
        disabledDate (date) {
          return date && date.valueOf() < Date.now() - 86400000
        }
      },
      poolConfig: {}
    }
  },

  watch: {
    guardM3DevicesIds (value, oldValue) {
      console.log('guardM3DevicesIds', value)
    },

    // 密码有效期默认和租期一样
    checkInDateStart (newVal) {
      // 租约开始日期
      // if (this.hasNoGatewayLock) return;
      this.passwordDateStart = newVal
    },
    checkInDateEnd (newVal) {
      // 租约结束日期
      if (this.hasNoGatewayLock && dayjs(newVal).valueOf() > dayjs(this.passwordDateStart).add(365, 'day').valueOf()) {
        this.passwordDateEnd = dayjs(this.passwordDateStart).add(365, 'day').toDate()
      } else {
        this.passwordDateEnd = newVal
      }
    },

    // 门锁密码类型改变
    passwordType (newVal) {
      if (newVal === 2) {
        this.tip() // 提示客户去app进行操作
        setTimeout(() => {
          this.passwordType = 1 // 切换会默认的授权密码
        }, 100)
      }
    }
  },
  mounted () {
    this.checkInDateStart = new Date()
    if (this.room) {
      const { id, home_id } = this.room
      // 用传进来的room信息会存在数据不能刷新的问题(例如预付费和后付费设置) 因此每次重新请求
      this.getRoomInfo(id)
      this.getAllLockDetail(id) // 非租客入口进入
      this.fetchM3AccessControll(id) // 获取m3门禁
      if (this.hasFaceAccessPermission) { // 只有在后台开通了人脸门禁授权才需要获取设备详情
        this.getAccessControllDetail(home_id)
      }
      return
    }
    this.getRenterById(this.renterId)
  },
  computed: {
    ...mapState({
      hasFaceAccessPermission: state => state.user.hasFaceAccessPermission
    }),

    passwordDateEndOptions () {
      return {
        disabledDate: (date) => {
          return this.hasNoGatewayLock ? date && (date.valueOf() < Date.now() - 86400000 || date.valueOf() > dayjs(this.passwordDateStart).add(365, 'day').valueOf()) : date && date.valueOf() < Date.now() - 86400000
        }
      }
    },

    isShowAddCoRenter () { // 有门禁关闭添加同租人按钮
      // console.log('length', this.corentersData.filter((coRenter) => (coRenter.relationship)).length);
      return (!this.hasFaceAccessPermission || (this.hasFaceAccessPermission && !this.guardDeviceIds.length)) && this.corentersData.length < 2
    },
    sendPasswordType () {
      return this.isShowTimeDeliveryTip ? '定时下发（密码将会在租约开始当天自动下发）' : '立即下发'
    },

    isShowTimeDeliveryTip () { // 是否展示定时下发提示,在门锁出现激活码密码而且租约时间大于等于现在开始的7天
      // console.log(dayjs(this.passwordDateStart).format('YYYY-MM-DD HH:mm:ss'), dayjs().startOf('day').add(1, 'day').format('YYYY-MM-DD HH:mm:ss'));
      return this.hasNoGatewayLock && dayjs(this.passwordDateStart).toDate() >= dayjs().startOf('day').add(1, 'day').toDate()
    },

    isShowUnableTip () {
      return this.hasNoGatewayLock && dayjs(this.passwordDateStart).toDate() >= dayjs().startOf('day').add(7, 'day').toDate()
    },

    overdraft () {
      // 计算房间是否是后付费
      return this.roomInfo.pay_type === 2
    },

    leftElectric () {
      if (!this.roomInfo.electric_read) {
        return 0
      }
      return util.getLeftElectric(this.roomInfo)
    },

    lockId () {
      let lockId
      this.roomInfo.devices.forEach(item => {
        if (item.device_type === DeviceTypeEnum.LOCK) {
          lockId = item.id
        }
      })
      return lockId
    },

    hasElemeter () {
      let selfHas // 本房间是否有设备
      if (this.roomInfo.devices) {
        selfHas = this.roomInfo.devices.some(item => {
          return item.device_type === DeviceTypeEnum.ELEMETER
        })
      }

      return selfHas // 房间有电表才显示电表相关
    },

    hasNoGatewayLock () { // 是否存在无网关或者离线的门锁
      if (!this.locks.length) {
        return true
      }
      if (this.isSendOutDoorPwd) { // 如果同时下发外门锁，必须两个门锁都可以发送在线密码
        return this.locks.some((lock) => (lock.can_send_online_password === false))
      } else { // 只下发内门锁，判断内门锁是否可以下发在线密码
        const innerLock = this.locks.find((lock) => (lock.is_public === false))
        return innerLock && innerLock.can_send_online_password === false
      }
    },

    /**
        * 公区设备
        */
    publicDevice () {
      return this.guardDevices.filter((device) => device.is_public)
    },

    /**
        * 单元门设备
        */
    privateDevice () {
      return this.guardDevices.filter((device) => !device.is_public)
    }
  },
  methods: {
    /**
        * 获取m3门禁信息
        */
    async fetchM3AccessControll (roomId) {
      this.m3AccessLoading = true
      try {
        this.guardM3Devices = await http.fetch(this, api.m3_pre_add_tenant_info, [roomId])

        this.guardM3DevicesIds = this.guardM3Devices.map((device) => (device.id))
      } catch (error) {
        console.log('err', error)
      } finally {
        this.m3AccessLoading = false
      }
    },

    selectRoom (homeId) {
      this.homeId = homeId || ''
      this.checkInRoomId = ''
      this.rooms = []
      const { lease_type } = this.homes.find((home) => (home.id === Number(homeId)))
      if (lease_type) {
        this.homeLeaseType = lease_type
      }
    },

    // 返回房源地址，如有楼栋则加上
    getHomeAddr () {
      const home = this.home
      const room = this.room
      if (!home || !room) {
        return '未知'
      }

      let addr = home.city + home.district + home.address
      const buildings = home.buildings
      if (room.building_id && buildings) {
        for (let i in buildings) {
          if (buildings[i].id === room.building_id) {
            addr += (' - ' + buildings[i].room_name)
            break
          }
        }
      }

      return addr
    },

    /**
         *  获取门禁列表
         */
    async getAccessControllDetail (homeId) {
      this.accessLoading = true
      try {
        this.guardDevices = await http.fetch(this, api.home_face_access, [homeId])

        this.guardDeviceIds = this.guardDevices.map((device) => (device.id))
      } catch (err) {
        console.log('err', err)
      } finally {
        this.accessLoading = false
      }
    },

    getAllLockDetail (roomId) { // 获取内外门锁信息
      this.lockLoading = true
      http.request(this, api.room_lock_detail, [roomId], null, (res, error) => {
        this.lockLoading = false
        if (error || !res) {
          return
        }
        const { locks, can_batch_delete_pwds } = res
        this.locks = locks
        this.hasLock = locks.length > 0
        this.canBatchDeletePwds = can_batch_delete_pwds // 是否可以删除所有非管理员密码
        this.hasOutLock = locks.some((value) => (value.is_public === true)) // 是否有外门锁
        if (!this.hasOutLock) {
          this.isSendOutDoorPwd = false
        }
      })
    },

    /**
         * 通过model型号判断该门锁是否是指纹门锁
         * @param {String} model 门锁型号
         */
    isFinger (model) {
      return model.split('-')[1] === '19'
    },

    /**
         * 提示客户区app上操作
         */
    tip () {
      const content = '<p>请通过App执行此操作</p>'
      const title = '提示'
      const config = {
        title,
        content
      }

      this.$Modal.success(config)
    },

    reset () {
      // 关闭弹窗
      this.isModalVisible = false
      this.operateResult = []
      this.isShowPwdTip = false // 初始化数据
      this.showAccessControllTip = false
      this.AccessControllTip = ''
    },

    resetForm (name) {
      this.$refs[name].resetFields()
    },

    handleTimePickerChange (value) {
      const now = Date.now()
      if (!value && this.checkInDateStart < new Date()) {
        this.checkInDateStart = new Date(now)
        // this.checkInDateEnd = new Date(now + 30 * 24 * 60 * 60 * 1000)
      }
    },

    handleTimePickerChange2 (value) {
      // 结束时间00:00:00调整为默认 23:59:59
      if (!value) {
        const time = this.checkInDateEnd.Format('HH:mm:ss')
        if (time === '00:00:00') {
          this.checkInDateEnd = new Date(this.checkInDateEnd.getTime() + 24 * 60 * 60 * 1000 - 1000)
        }
      }
    },

    validateIdCard (value) {
      const reg = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/

      return reg.test(value)
    },

    confirmAddRenter (name) {
      // 添加租客
      if (this.isLoadig) {
        return
      }
      this.$refs[name].validate(valid => {
        if (valid) {
          let params = this.formItem

          const phoneReg = /^1\d{10}$/
          if (params.country_code === '86' && !phoneReg.test(params.phone)) {
            this.$Message.info('手机号格式错误')
            return
          }

          if (!params.id_card) {
            delete params.id_card
          } else {
            const flag = this.validateIdCard(params.id_card) // 检验身份证号

            if (!flag) {
              this.$Message.error('请输入正确的身份证号码!')
              return
            }
          }
          this.isLoadig = true
          http.request(this, api.tenant_create, null, params, res => {
            if (res) {
              this.isLoadig = false
              this.showAddRenter = false
              this.getRenterById(res.tenant_id)
              this.$Message.success('增加租客成功!')
            } else {
              this.isLoadig = false
            }
          })
        }
      })
    },

    cancelAddRenter (name) {
      // 取消添加租客
      this.resetForm(name)
      this.showAddRenter = false
    },

    getRenterById (renterId) {
      http.request(this, api.tenant_info, [renterId], null, res => {
        if (res) {
          // 获取到租客信息
          this.renter = res
        }
      })
    },

    confirmCheckIn () {
      // 租客入住
      if (!this.renter.name) {
        this.$Message.error('请选择租客!')
        return
      }

      if (!this.roomInfo.id) {
        this.$Message.error('请选择入住房间!')
        return
      }

      if (this.checkInDateStart === 0) {
        this.$Message.error('请选择租约开始日期!')
        return
      }

      if (this.checkInDateEnd === 0) {
        this.$Message.error('请选择租约结束日期!')
        return
      }

      if (new Date(this.checkInDateEnd) - new Date(this.checkInDateStart) <= 4 * 60 * 60 * 1000) {
        this.$Message.error('租期必须大于4小时!')
        return
      }

      if (this.checkInDateEnd < this.passwordDateEnd) {
        this.$Message.error('密码有效期不能大于租约有效期!')
        return
      }

      if (this.passwordType && new Date(this.passwordDateEnd) - new Date(this.passwordDateStart) < 0) {
        this.$Message.error('密码有效期选择错误!')
        return
      }

      this.checkInFormItem.lease_start = new Date(this.checkInDateStart).getTime()
      this.checkInFormItem.lease_end = new Date(this.checkInDateEnd).getTime()

      // 清除空的同租人对象
      this.corentersData = this.corentersData.filter(item => {
        return item.tenant_id
      })

      // 判断是否有相同同租人或者同租人为该租客的情况
      let pos = false // 判断同租人和承租人是否是一个人
      let obj = {}
      let flag = this.corentersData.every(x => {
        let id = x.tenant_id
        if (obj[id]) {
          // 存在相同同租人
          return false
        } else if (id === this.renter.id) {
          // 同租人和承租人为同一人
          pos = true
          return false
        } else {
          obj[id] = true
          return true
        }
      })

      if (!flag) {
        // 如果存在相同的同租人或者承租人和同租人为同一个人
        this.$Message.error(pos ? '同租人和承租人不能为同一人!' : '不能添加相同的同租人!')
        return
      }

      // 若未添加备注，则为 无
      this.checkInFormItem.co_tenants = this.corentersData
      if (!this.checkInFormItem.note) {
        this.checkInFormItem.note = '无'
      }

      let room_id = this.roomInfo.id // 房间id
      let tenant_id = this.renter.id // 租客id

      if (this.hasFaceAccessPermission && this.guardDevices.length && !this.guardDeviceIds.length) {
        this.$Message.error('必须选择要下发的门禁设备!')
        return
      }

      // if (this.guardM3Devices.length && !this.guardM3DevicesIds.length) {
      //     this.$Message.error('必须选择要下发的门禁设备!');
      //     return;
      // }

      this.isLoadig = true

      http.request(this, api.tenant_checkin, [tenant_id, room_id], this.checkInFormItem, async (res) => {
        if (res) {
          this.reset()
          this.clearElemeter()

          if (this.guardDeviceIds.length || this.guardM3DevicesIds.length) { // 下发人脸门禁授权
            this.M3AccessControllTip = ''
            this.AccessControllTip = ''
            try {
              if (this.guardM3DevicesIds.length) {
                await this.m3Authorize(res.lease_id, this.guardM3DevicesIds) // 访客下发人脸授权
                this.M3AccessControllTip = 'M3门禁授权指令下发成功, 请去门禁授权列表检查相应门禁授权状态'
              }

              if (this.guardDeviceIds.length) {
                await this.authorize(tenant_id, res.lease_id, !this.room ? this.homeId : this.room.home_id) // 访客下发人脸授权
                this.AccessControllTip = '人脸门禁授权指令下发成功, 请去门禁授权列表检查相应门禁授权状态'
              }
            } catch (err) {
              this.AccessControllTip = `人脸门禁授权指令下发失败, 由于${err && err.data && err.data.err_msg}`
            } finally {
              this.showM3AccessControllTip = true
              this.showAccessControllTip = true
            }
          }

          if (this.passwordType && this.hasLock) { // 如果有门锁并且选择授权
            this.isShowPwdTip = true
            this.givePassword(res.lease_id) // 密码操作
          } else {
            this.isShowPwdModal = true
          }
        }
        this.isLoadig = false
      })
    },

    async m3Authorize (lease_id, device_ids) {
      return await http.fetch(this, api.m3_tenant_auth_add, [lease_id], {device_ids}, true)
    },

    /**
        * 访客下发授权
        */
    async authorize (relation_id, lease_id, home_id) {
      const params = {
        auth_start_time: new Date(this.checkInDateStart).valueOf(),
        auth_end_time: new Date(this.checkInDateEnd).valueOf(),
        device_ids: this.guardDeviceIds,
        relation_role: 2,
        relation_id,
        lease_id
      }

      return await http.fetch(this, api.face_access_add, [home_id], params, true)
    },

    // 租客入住之后执行
    doAfterCheckIn () {
      this.isShowPwdModal = false
      if (this.operateResult.length) { // 展示进度条
        this.isResultModalVisible = true
      } else {
        this.$emit('checkInSuccess')
      }
    },

    closeOutModal () {
      this.$emit('checkInSuccess')
    },

    cancelCheckIn () {
      this.$emit('cancelCheckIn')
    },

    givePassword (lease_id) {
      // 授权密码
      // 授权密码 并且 有门锁
      let room_id = this.roomInfo.id
      let country_code = this.renter.country_code || '86'

      const params = {
        batch_delete_pwds: this.deleteAllNotRenterPassword,
        password_type: 1,
        country_code,
        // name: this.renter.name,
        room_id: room_id,
        lease_id: lease_id,
        tenant_id: this.renter.id,
        // phonenumber: this.renter.phone,
        is_send_location: this.smsWithHome,
        permission_status: 2,
        multi_type: 3, // 默认为内外门都下发
        permission_begin: this.passwordDateStart ? new Date(this.passwordDateStart).getTime() : new Date(this.checkInDateEnd).getTime(),
        permission_end: this.passwordDateEnd ? new Date(this.passwordDateEnd).getTime() : new Date(this.checkInDateStart).getTime()
      }

      if (!this.isSendOutDoorPwd) {
        // 如果只内门下发
        params.multi_type = 1
      }

      util.log('是否有 无网关/离线 门锁', !!this.hasNoGatewayLock)

      const sendPasswordApi = !this.hasNoGatewayLock ? api.password_send_multi : api.password_send_active_multi
      util.log(!this.hasNoGatewayLock ? '在线密码下发' : '离线密码下发')

      http.request(this, sendPasswordApi, [room_id], params, (res, error) => {
        if (error) {
          return
        }

        this.batchResult = {}

        if (res && res.batch_delete_result) {
          this.batchResult = res.batch_delete_result
        }

        if (this.corentersData.length) {
          this.sendCoRenterPWd(sendPasswordApi, room_id, params)
        }

        this.isShowPwdModal = true
      })
    },

    sendCoRenterPWd (sendPasswordApi, room_id, params) {
      this.corentersData.map((corenter) => {
        const { tenant_id } = corenter
        http.request(this, sendPasswordApi, [room_id], {...params, tenant_id}, (res, error) => {}, false)
      })
    },

    clearElemeter () {
      // 清空电表
      if (this.isResetElemeter && this.hasElemeter) {
        const roomId = this.roomInfo.id

        this.operateResult.push({
          params: [api.room_elemeter_reset, [roomId], null],
          title: '剩余电量清零'
        })
      }
    },
    remoteMethod: util.throttle(function (query) {
      // 搜索房源
      if (query !== '') {
        /** 防止点击清除搜索结果 */
        // if (/\(房源编号:.+\)/.test(query)) return;
        let params = {
          keyword: query
        }
        this.loadingHome = true
        http.request(this, api.home_list, null, params, res => {
          if (res) {
            this.homes = res.homes
          }
          this.loadingHome = false
        })
      }
      // else {
      //     this.homes = [];
      // }
    }),
    addRenter () {
      this.showAddRenter = true
    },
    remoteRenterMethod (query) {
      // 搜索租客
      if (query !== '') {
        let params = {
          keyword: query,
          limit: 500
        }
        this.loadingRenter = true
        http.request(this, api.tenant_list, null, params, res => {
          if (res) {
            this.searchedRenters = res.list
          }
          this.loadingRenter = false
        })
      } else {
        this.searchedRenters = []
      }
    },
    selectRenter (renterId) {
      if (renterId) {
        this.getRenterById(renterId)
      }
    },
    searchRoom (homeId, ratios, keyword = '', roomType) {
      // 搜索房间
      if (!homeId) {
        return
      }
      this.homeId = homeId

      let params = keyword ? {
        with_building: 1,
        room_type: roomType || 'commonRoom',
        keyword,
        with_tenant: 1
      } : {
        with_tenant: 1
      }

      keyword && (this.loadingRoom = true)

      http.request(this, api.room_list, [homeId], params, async (res) => {
        this.loadingRoom = false
        if (res) {
          const rooms = res.filter(room => !room.leases.length)
          this.rooms = rooms
          if (ratios) this.setRoomRatios(ratios)
        }
      })
    },

    getRooms: util.throttle(function (keyword) {
      if (!this.homeId) {
        return
      }

      if (keyword === '') {
        this.rooms = []
      } else {
        this.searchRoom(this.homeId, false, keyword, this.homeLeaseType === 1 ? 'room' : 'publicRoom')
      }
    }),

    getRoomInfo (roomId) {
      // 获取房间具体信息
      if (!roomId) {
        return
      }

      this.checkInRoomId = roomId
      http.request(this, api.room_info, [roomId], null, res => {
        if (res) {
          this.roomInfo = res
          if (!this.room) {
            this.getAllLockDetail(res.id)
            this.fetchM3AccessControll(res.id)
            if (this.hasFaceAccessPermission) { // 只有在后台开通了人脸门禁授权才需要获取设备详情
              this.getAccessControllDetail(this.roomInfo.home_id)
            }
          }
        }
      })
    },
    addCorenter () {
      // 添加同租人总数
      this.coRenterNumber++
      this.corentersData.push({})
    },
    addCorenterData (data, idx) {
      // 添加同租人数据,用于提交
      this.corentersData[idx] = data
      // console.log(this.corentersData);
    },
    removeCorenterData (idx) {
      // 删除同租人数据,用于提交
      this.coRenterNumber--
      this.corentersData[idx] = {}
      // console.log(this.corentersData);
    },

    getPoolCfg (homeId) {
      http.request(this, api.home_pool_setting_info, [homeId], null, res => {
        // 获取公摊设置
        if (res) {
          this.poolConfig = res
          if (this.room) {
            this.searchRoom(this.room.home_id, res.ratios)
          } else {
            this.setRoomRatios(res.ratios)
          }
        }
      })
    },

    setRoomRatios (ratios) {
      this.rooms.forEach(item => {
        const roomId = item.id
        // 有租客的房间或者当前房间 才计算公摊比例
        if ((item.leases && item.leases.length) || this.roomInfo.id === roomId) {
          item.ratio = (ratios[roomId] && ratios[roomId].ratio) || 0
        } else {
          item.ratio = 0
        }
      })
      util.log(this.rooms)
    },

    handlePopperShow () {
      if (this.room) {
        this.getPoolCfg(this.room.home_id)
      } else if (this.homeId) {
        this.getPoolCfg(this.homeId)
      }
    },

    getTotalRatios (rooms) {
      let result = 0
      rooms.forEach(item => {
        const roomId = item.id
        // 有租客的房间或者当前房间 计算公摊总比例
        if ((item.leases && item.leases.length) || this.roomInfo.id === roomId) {
          result += item.ratio
        }
      })
      return result || 1
    }
  }
}
</script>

<style lang="less">
.renter-info {
    height: 38px;
    line-height: 38px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.mb10 {
    margin-bottom: 18px;
}
.cursor-text {
    cursor: text;
    input {
        cursor: text;
    }
}
.pool-content {
    padding: 10px;
    max-height: 300px;
    overflow: auto;
}
.lock-wrap {
    width: 100%;
    height: 143px;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
}

.access-control-wrap {
    width: 100%;
    height: 100px;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
